var conn = (function(){

	var _ws;
	var username;
	var responseHandlers=new Array();
	
	function join(name){
		username=name;
		var location = window.location.href.replace('http:', 'ws:').replace('main.html', 'Wsservlet');
		$('#notifications').append("Connecting to " +  location + "<br />");
		_ws=new WebSocket(location);
		_ws.onopen=_onopen;
		_ws.onmessage=_onmessage;
		_ws.onclose=_onclose;
	}
	
	function _onopen(){
		$('#notifications').append("Connected<br />" );
		_ws.send("name|" + username);
	}
	
	function send(messageObj, to, echoToMe){
		messageObj.from=username;
		if(to)messageObj.to=to;
		var message=JSON.stringify(messageObj);
		_ws.send( (echoToMe?"":username) + "|" + (to?to:"") + "|" + message);
	}
	
	function _onmessage(m) {
		  if (m.data){
			  if(m.data.indexOf("\"type\":\"paint\"")==-1)
				  $('#notifications').append("Received: " +  m.data + "<br />");
			  try{
				  var objM = JSON.parse(m.data);
				  if(objM.type && responseHandlers[objM.type]){
					  responseHandlers[objM.type](objM);
				  }
			  }catch(ex){
				  
			  }
			  
			  //var obj = jQuery.parseJSON(m.data.substring(8));
			  //$('#notifications').append(m.data.substring(0,7) + " " + obj.x + " " + obj.y +  "<br />");
			  //draw(m.data.substring(0,7), obj.x, obj.y);
			  //$('#notifications').append(m.data.substring(8)+"<br />");
		  }
	}
	
	function addResponseHandler(type, fn){
		responseHandlers[type]=fn;
	}
	
	function _onclose(){
		
	}
	
	function getUsername(){return username;}

	return{
		join:join,
		ws:_ws,
		send:send,
		addResponseHandler:addResponseHandler,
		getUsername:getUsername 
	};

})();

//==============================================================================

var paint = (function(){

	var canvas;
	var ctx;
	var canvasOffset;
	
	var mouseDown = 0;
	
	function init (canvasID){
		
		canvas = document.getElementById(canvasID);
		canvas.width=340;
		canvas.height=270;
		
		ctx = canvas.getContext('2d');

		$(canvas)
			.mousedown(function() { ++mouseDown; })
			.mouseup(function() { --mouseDown; })
			.mousemove(function(e){
			if(mouseDown){
				if(!canvasOffset) canvasOffset = $(canvas).offset();
				conn.send({"type":"paint","x":e.pageX-canvasOffset.left,"y":e.pageY-canvasOffset.top});				
				draw(e.pageX-canvasOffset.left, e.pageY-canvasOffset.top);
			}
		});
		
	}
	
	function draw(x,y){
		//$('#notifications').append("X: " +  canvasOffset.left + " y:"+y+"<br />");
		ctx.fillStyle = '#000';		
		ctx.fillRect(x-2,y-2,4,4);   // Draw a rectangle with restored settings  
	}
	
	function clearHandler(){
		ctx.save();
		ctx.fillStyle = '#fff';
		ctx.fillRect(0,0,500,500);   // Draw a rectangle with default settings
		ctx.restore();
	}
	
	function paintHandler(elObj){
		draw(elObj.x, elObj.y);
	}
	
	function getRandColor(){
		return '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
	}
	
	return {
		init:init,
		ctx:ctx, 
		draw:draw,
		getRandColor:getRandColor,
		paintHandler:paintHandler, 
		clearHandler:clearHandler
	};
	
})();

//==============================================================================

var chat = (function(){
	
	function usersListHandler(objM){
		$("#connectedUsers").empty();
		$.each(objM.list,function(index,value){
		});
	}
	
	function imMessageHandler(objM){
		$("#chatWindow").append("<div><span class=\"sender\">"+objM.from+":</span> "+objM.message+"</div>");
	}
	
	return{
		usersListHandler:usersListHandler,
		imMessageHandler:imMessageHandler
	};
	
})();

//==============================================================================
$(document).ready(function(){

	$('#btnJoin').click(function(){
		conn.join($("#name").val());
		$('#login').hide();
		$("#app").show();
		
	});
	
	function sendMessage(){
		conn.send({"type":"im","message":$("#txt1").val()},null,true);
		$("#txt1").val("").focus();
	}
	
	$("#boton").click(sendMessage);
	$("#txt1").keydown(function(event){if (event.keyCode == 13)sendMessage();});
	
	
	//Assign Message Handlers
	conn.addResponseHandler("usersList", chat.usersListHandler);
	conn.addResponseHandler("im", chat.imMessageHandler);
	conn.addResponseHandler("paint", paint.paintHandler);
	conn.addResponseHandler("paintClear", paint.clearHandler);
	
	paint.init("canvas");
	
	$("#clearBtn").click(function(){ conn.send({"type":"paintClear"},null,true); });
	
});
